<template>
  <div class="box">
    <div class="tit" data-icon="chart">
      <div class="tit-content">
        <span class="tit-main">业务发展</span>
        <transition name="group-name-fade" mode="out-in">
          <span :key="currentGroupIndex" class="group-name">{{ currentGroupName }}</span>
        </transition>
      </div>
      <div class="bottom-line"></div>
    </div>
    <div class="boxnav" style="height: 220px; padding: 4px; overflow: hidden;" @mouseenter="isPaused = true" @mouseleave="isPaused = false">
      <div class="business-container">
        <!-- 业务指标组 -->
        <transition name="group-fade" mode="out-in">
          <div :key="currentGroupIndex" class="metrics-group">
            <!-- 贷款和存款业务：显示指标卡片 -->
            <div v-if="businessGroups[currentGroupIndex].key !== 'digital'" class="metrics-container">
              <div 
                v-for="(metric, idx) in currentMetrics" 
                :key="metric.key"
                class="metric-item"
                :style="getMetricAccentStyle(idx)"
              >
                <div class="metric-content">
                  <div class="metric-info">
                    <div class="metric-label">{{ metric.label }}</div>
                    <div class="metric-value">
                      <div class="value-main">
                        <span class="value">{{ metric.value }}</span>
                        <span v-if="metric.unit" class="value-unit">{{ metric.unit }}</span>
                        <span v-if="!metric.changeValue" class="trend" :class="metric.trendClass">{{ metric.trendIcon }}</span>
                      </div>
                      <div v-if="metric.changeValue" class="value-change-row">
                        <span 
                          class="value-change" 
                          :class="metric.changeClass"
                        >
                          <span class="change-type">同比</span>
                          {{ metric.changeValue }}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div class="metric-chart">
                    <div class="mini-trend-chart_ver">
                      <MiniTrendChart :data="metric.trendData" :width="120" :height="30" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 数字化转型：显示饼图 -->
            <div v-else class="digital-chart-container">
              <div ref="digitalChartRef" class="digital-chart"></div>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useIndicatorAPI } from '../composables/useIndicatorAPI.js'
import MiniTrendChart from './MiniTrendChart.vue'

const { getIndicatorData } = useIndicatorAPI()

// 数字化饼图引用
const digitalChartRef = ref(null)
let digitalChartInstance = null

// 业务指标分组配置
const businessGroups = [
  {
    groupName: '贷款业务',
    key: 'loan'
  },
  {
    groupName: '存款业务', 
    key: 'deposit'
  }
  // {
  //   groupName: '数字化转型',
  //   key: 'digital'
  // }
]

// 贷款数据
const loanData = ref({
  totalAmount: '0.00',      // 贷款总余额(亿)
  totalGrowthRate: '+0.0%', // 同比增速
  retailRatio: '0.0%',      // 零售贷款占比
  retailRatioChange: '+0.0%', // 零售贷款占比同比变化
  realEstateGrowthRate: '+0.0%', // 房地产贷款比年初增速
  realEstateChange: '+0.0%' // 房地产贷款增速同比变化
})

// 存款数据
const depositData = ref({
  totalAmount: '0.00',      // 存款总余额(亿)
  totalGrowthRate: '+0.0%', // 同比增速
  lowCostRatio: '0.0%',     // 低成本存款占比
  lowCostRatioChange: '+0.0%', // 低成本存款占比同比变化
  topTenRatio: '0.0%',      // 最大十户存款比例
  topTenRatioChange: '+0.0%' // 最大十户存款比例同比变化
})

// 贷款趋势数据
const loanTrendData = ref({
  total: [],      // 总贷款趋势
  retail: [],     // 零售贷款趋势
  realEstate: []  // 房地产贷款趋势
})

// 存款趋势数据
const depositTrendData = ref({
  total: [],      // 总存款趋势
  lowCost: [],    // 低成本存款趋势
  topTen: []      // 最大十户存款趋势
})

// 数字化转型渠道数据（用于饼图）
const digitalChannelData = ref([])

// 定义各个渠道的指标名称和显示名称
const channelIndicators = [
  { name: '传统设备月交易量', displayName: '传统设备' },
  { name: '企业手机银行月交易笔数', displayName: '企业手机银行' },
  { name: '个人网上银行月交易笔数', displayName: '个人网上银行' },
  { name: '企业网上银行月交易笔数', displayName: '企业网上银行' },
  { name: '个人手机银行月交易笔数', displayName: '个人手机银行' },
  { name: '线下渠道月交易量', displayName: '线下渠道' },
  { name: '智能设备月交易量', displayName: '智能设备' },
  { name: '柜面渠道月交易量', displayName: '柜面渠道' }
]

// 轮播相关状态
const currentGroupIndex = ref(0)
const currentGroupName = ref(businessGroups[0].groupName)
const isTransitioning = ref(false)
const isPaused = ref(false)
let carouselTimer = null
// 左侧色条样式：为同一行的三张卡片提供区分色
const metricAccentColors = ['#29D9D5', '#3C8BFF', '#FF8A65']
const getMetricAccentStyle = (idx) => {
  const color = metricAccentColors[idx % metricAccentColors.length]
  return {
    borderLeft: `3px solid ${color}`,
    boxShadow: `inset 0 0 0 1px rgba(255,255,255,0.06), 0 0 10px ${color}33`
  }
}

// 当前显示的指标组
const currentMetrics = computed(() => {
  const currentGroup = businessGroups[currentGroupIndex.value]
  
  if (currentGroup.key === 'loan') {
    return [
      {
        key: 'loan-total',
        label: '总贷款',
        value: `${loanData.value.totalAmount}`,
        unit: '亿',
        changeValue: loanData.value.totalGrowthRate,
        changeClass: loanData.value.totalGrowthRate.startsWith('+') ? 'change-up' : 'change-down',
        changeDirection: loanData.value.totalGrowthRate.startsWith('+') ? '+' : '',
        trendIcon: loanData.value.totalGrowthRate.startsWith('+') ? '📈' : '📉',
        trendClass: loanData.value.totalGrowthRate.startsWith('+') ? 'up' : 'down',
        trendData: loanTrendData.value.total
      },
      {
        key: 'loan-retail',
        label: '零售贷款',
        value: loanData.value.retailRatio,
        changeValue: loanData.value.retailRatioChange,
        changeClass: loanData.value.retailRatioChange.startsWith('+') ? 'change-up' : 'change-down',
        changeDirection: loanData.value.retailRatioChange.startsWith('+') ? '+' : '',
        trendIcon: loanData.value.retailRatioChange.startsWith('+') ? '📈' : '📉',
        trendClass: loanData.value.retailRatioChange.startsWith('+') ? 'up' : 'down',
        trendData: loanTrendData.value.retail
      },
      {
        key: 'loan-realestate',
        label: '房地产贷款',
        value: loanData.value.realEstateGrowthRate,
        changeValue: loanData.value.realEstateChange,
        changeClass: loanData.value.realEstateChange.startsWith('+') ? 'change-up' : 'change-down',
        changeDirection: loanData.value.realEstateChange.startsWith('+') ? '+' : '',
        trendIcon: loanData.value.realEstateChange.startsWith('+') ? '📈' : '📉',
        trendClass: loanData.value.realEstateChange.startsWith('+') ? 'up' : 'down',
        trendData: loanTrendData.value.realEstate
      }
    ]
  } else if (currentGroup.key === 'deposit') {
    return [
      {
        key: 'deposit-total',
        label: '总存款',
        value: `${depositData.value.totalAmount}`,
        unit: '亿',
        changeValue: depositData.value.totalGrowthRate,
        changeClass: depositData.value.totalGrowthRate.startsWith('+') ? 'change-up' : 'change-down',
        changeDirection: depositData.value.totalGrowthRate.startsWith('+') ? '+' : '',
        trendIcon: depositData.value.totalGrowthRate.startsWith('+') ? '📈' : '📉',
        trendClass: depositData.value.totalGrowthRate.startsWith('+') ? 'up' : 'down',
        trendData: depositTrendData.value.total
      },
      {
        key: 'deposit-lowcost',
        label: '低成本存款',
        value: depositData.value.lowCostRatio,
        changeValue: depositData.value.lowCostRatioChange,
        changeClass: depositData.value.lowCostRatioChange.startsWith('+') ? 'change-up' : 'change-down',
        changeDirection: depositData.value.lowCostRatioChange.startsWith('+') ? '+' : '',
        trendIcon: depositData.value.lowCostRatioChange.startsWith('+') ? '📈' : '📉',
        trendClass: depositData.value.lowCostRatioChange.startsWith('+') ? 'up' : 'down',
        trendData: depositTrendData.value.lowCost
      },
      {
        key: 'deposit-topten',
        label: '最大十户存款',
        value: depositData.value.topTenRatio,
        changeValue: depositData.value.topTenRatioChange,
        changeClass: depositData.value.topTenRatioChange.startsWith('+') ? 'change-up' : 'change-down',
        changeDirection: depositData.value.topTenRatioChange.startsWith('+') ? '+' : '',
        trendIcon: depositData.value.topTenRatioChange.startsWith('+') ? '📈' : '📉',
        trendClass: depositData.value.topTenRatioChange.startsWith('+') ? 'up' : 'down',
        trendData: depositTrendData.value.topTen
      }
    ]
  } else {
    // 数字化转型显示饼图，不返回指标
    return []
  }
})

// 查询可用的指标名称
const queryAvailableIndicators = async () => {
  try {
    const sql = `select distinct index_nm from audit_index_total where index_nm like '%贷款%' or index_nm like '%存款%' order by index_nm`
    const result = await getIndicatorData('查询指标')
    console.log('数据库中可用的指标:', result)
  } catch (error) {
    console.error('查询指标名称失败:', error)
  }
}

// 数据加载函数
const loadBusinessData = async () => {
  try {
    console.debug('[RiskRadar] 开始加载业务发展数据...')
    
    // 先查询可用指标（用于调试）
    // await queryAvailableIndicators()
    
    // 尝试多种可能的指标名称
    const possibleLoanNames = ['贷款总余额', '贷款余额', '各项贷款', '贷款总额']
    const possibleRetailNames = ['零售类贷款本期余额', '零售贷款余额', '个人贷款余额', '零售贷款']
    const possibleRealEstateNames = ['房地产贷款比年初增速', '房地产贷款', '房地产开发贷款', '涉房贷款']
    const possibleDepositNames = ['各项存款', '存款余额', '存款总余额', '存款总额']
    const possibleDemandNames = ['单位活期存款', '对公活期存款', '企业活期存款']
    const possiblePersonalNames = ['个人活期存款', '储蓄活期存款', '个人储蓄存款']
    const possibleTopTenNames = ['最大十户存款比例', '最大十户存款集中度', '大户存款比例']
    
    // 并行获取各项指标数据
    const [
      loanTotalResult,
      retailLoanResult,
      realEstateLoanResult,
      depositTotalResult,
      demandDepositResult,
      personalDepositResult,
      topTenDepositResult
    ] = await Promise.allSettled([
      getIndicatorData(possibleLoanNames[0]),
      getIndicatorData(possibleRetailNames[0]),
      getIndicatorData(possibleRealEstateNames[0]), // 直接使用房地产贷款比年初增速
      getIndicatorData(possibleDepositNames[0]),
      getIndicatorData(possibleDemandNames[0]),
      getIndicatorData(possiblePersonalNames[0]),
      getIndicatorData(possibleTopTenNames[0])
    ])

    // 处理贷款数据
    if (loanTotalResult.status === 'fulfilled' && loanTotalResult.value) {
      console.log('贷款总余额API响应:', loanTotalResult.value)
      const loanTotal = loanTotalResult.value.datas || loanTotalResult.value.data
      if (loanTotal && loanTotal.length >= 1) {
        // 检查数据结构
        console.log('贷款数据结构:', loanTotal[0])
        const current = parseFloat(loanTotal[0][3] || loanTotal[0].index_vl || loanTotal[0].index_value || 0)
        const previous = loanTotal.length >= 2 ? parseFloat(loanTotal[1][3] || loanTotal[1].index_vl || loanTotal[1].index_value || 0) : current * 0.9
        
        // 转换为亿元
        loanData.value.totalAmount = (current / 100000000).toFixed(2)
        
        // 计算同比增速
        if (previous > 0) {
          const growthRate = ((current - previous) / previous * 100).toFixed(1)
          loanData.value.totalGrowthRate = `${growthRate > 0 ? '+' : ''}${growthRate}%`
        }
        
        // 生成总贷款趋势数据（取最近6个月数据）
        loanTrendData.value.total = loanTotal.slice(0, 6).reverse().map((item, index) => {
          const value = parseFloat(item[3] || item.index_vl || item.index_value || 0) / 100000000
          const date = item[0] || `${2024 + Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`
          return { value: value, date: date }
        })
      }
    }

    // 处理零售贷款占比
    if (retailLoanResult.status === 'fulfilled' && retailLoanResult.value && 
        loanTotalResult.status === 'fulfilled' && loanTotalResult.value) {
      console.log('零售贷款API响应:', retailLoanResult.value)
      const retailLoanData = retailLoanResult.value.datas || retailLoanResult.value.data
      const totalLoanData = loanTotalResult.value.datas || loanTotalResult.value.data
      
      const retailLoan = parseFloat(retailLoanData?.[0]?.[3] || retailLoanData?.[0]?.index_vl || retailLoanData?.[0]?.index_value || 0)
      const totalLoan = parseFloat(totalLoanData?.[0]?.[3] || totalLoanData?.[0]?.index_vl || totalLoanData?.[0]?.index_value || 0)
      
      if (totalLoan > 0) {
        const ratio = ((retailLoan / totalLoan) * 100).toFixed(1)
        loanData.value.retailRatio = `${ratio}%`
        
        // 计算同比变化（如果有历史数据）
        if (retailLoanData.length >= 2 && totalLoanData.length >= 2) {
          const retailLoanPrev = parseFloat(retailLoanData[1][3] || retailLoanData[1].index_vl || retailLoanData[1].index_value || 0)
          const totalLoanPrev = parseFloat(totalLoanData[1][3] || totalLoanData[1].index_vl || totalLoanData[1].index_value || 0)
          
          if (totalLoanPrev > 0) {
            const prevRatio = (retailLoanPrev / totalLoanPrev) * 100
            const ratioChange = (parseFloat(ratio) - prevRatio).toFixed(1)
            loanData.value.retailRatioChange = `${ratioChange > 0 ? '+' : ''}${ratioChange}%`
          }
        }
      }
      
      // 生成零售贷款占比趋势数据
      if (retailLoanData && totalLoanData) {
        const minLength = Math.min(retailLoanData.length, totalLoanData.length, 6)
        loanTrendData.value.retail = []
        for (let i = 0; i < minLength; i++) {
          const retailValue = parseFloat(retailLoanData[i][3] || retailLoanData[i].index_vl || retailLoanData[i].index_value || 0)
          const totalValue = parseFloat(totalLoanData[i][3] || totalLoanData[i].index_vl || totalLoanData[i].index_value || 0)
          if (totalValue > 0) {
            const ratio = (retailValue / totalValue) * 100
            const date = retailLoanData[i][0] || `${2024 + Math.floor(i / 12)}-${String((i % 12) + 1).padStart(2, '0')}`
            loanTrendData.value.retail.unshift({ value: ratio, date: date })
          }
        }
      }
    }

    // 处理房地产贷款比年初增速（直接获取增速值）
    if (realEstateLoanResult.status === 'fulfilled' && realEstateLoanResult.value) {
      console.log('房地产贷款比年初增速API响应:', realEstateLoanResult.value)
      const realEstateData = realEstateLoanResult.value.datas || realEstateLoanResult.value.data
      if (realEstateData && realEstateData.length >= 1) {
        // 直接获取增速值，不需要计算
        const growthRateValue = parseFloat(realEstateData[0][3] || realEstateData[0].index_vl || realEstateData[0].index_value || 0)
        
        // 如果值已经是百分比形式（比如25.8），直接使用
        // 如果值是小数形式（比如0.258），则需要乘以100
        let displayValue = growthRateValue
        if (Math.abs(growthRateValue) < 1 && growthRateValue !== 0) {
          // 可能是小数形式，转换为百分比
          displayValue = growthRateValue * 100
        }
        
        loanData.value.realEstateGrowthRate = `${displayValue > 0 ? '+' : ''}${displayValue.toFixed(1)}%`
        
        // 计算房地产贷款增速的同比变化
        if (realEstateData.length >= 2) {
          const currentValue = displayValue
          let prevValue = parseFloat(realEstateData[1][3] || realEstateData[1].index_vl || realEstateData[1].index_value || 0)
          
          // 统一处理为百分比格式
          if (Math.abs(prevValue) < 1 && prevValue !== 0) {
            prevValue = prevValue * 100
          }
          
          const change = (currentValue - prevValue).toFixed(1)
          loanData.value.realEstateChange = `${change > 0 ? '+' : ''}${change}%`
        }
        
        // 生成房地产贷款增速趋势数据
        loanTrendData.value.realEstate = realEstateData.slice(0, 6).reverse().map((item, index) => {
          let value = parseFloat(item[3] || item.index_vl || item.index_value || 0)
          // 统一处理为百分比格式
          if (Math.abs(value) < 1 && value !== 0) {
            value = value * 100
          }
          const date = item[0] || `${2024 + Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`
          return { value: value, date: date }
        })
      }
    }

    // 处理存款数据
    if (depositTotalResult.status === 'fulfilled' && depositTotalResult.value) {
      console.log('各项存款API响应:', depositTotalResult.value)
      const depositTotal = depositTotalResult.value.datas || depositTotalResult.value.data
      if (depositTotal && depositTotal.length >= 1) {
        const current = parseFloat(depositTotal[0][3] || depositTotal[0].index_vl || depositTotal[0].index_value || 0)
        const previous = depositTotal.length >= 2 ? parseFloat(depositTotal[1][3] || depositTotal[1].index_vl || depositTotal[1].index_value || 0) : current * 0.92
        
        // 转换为亿元
        depositData.value.totalAmount = (current / 100000000).toFixed(2)
        
        // 计算同比增速
        if (previous > 0) {
          const growthRate = ((current - previous) / previous * 100).toFixed(1)
          depositData.value.totalGrowthRate = `${growthRate > 0 ? '+' : ''}${growthRate}%`
        }
        
        // 生成总存款趋势数据（取最近6个月数据）
        depositTrendData.value.total = depositTotal.slice(0, 6).reverse().map((item, index) => {
          const value = parseFloat(item[3] || item.index_vl || item.index_value || 0) / 100000000
          const date = item[0] || `${2024 + Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`
          return { value: value, date: date }
        })
      }
    }

    // 处理低成本存款占比 (单位活期+个人活期)/各项存款
    if (demandDepositResult.status === 'fulfilled' && personalDepositResult.status === 'fulfilled' &&
        depositTotalResult.status === 'fulfilled' && depositTotalResult.value) {
      console.log('单位活期存款API响应:', demandDepositResult.value)
      console.log('个人活期存款API响应:', personalDepositResult.value)
      
      const demandDepositData = demandDepositResult.value?.datas || demandDepositResult.value?.data
      const personalDepositData = personalDepositResult.value?.datas || personalDepositResult.value?.data
      const allDepositsData = depositTotalResult.value.datas || depositTotalResult.value.data
      
      const demandDeposit = parseFloat(demandDepositData?.[0]?.[3] || demandDepositData?.[0]?.index_vl || demandDepositData?.[0]?.index_value || 0)
      const personalDeposit = parseFloat(personalDepositData?.[0]?.[3] || personalDepositData?.[0]?.index_vl || personalDepositData?.[0]?.index_value || 0)
      const allDeposits = parseFloat(allDepositsData?.[0]?.[3] || allDepositsData?.[0]?.index_vl || allDepositsData?.[0]?.index_value || 0)
      
      if (allDeposits > 0) {
        const lowCostDeposit = demandDeposit + personalDeposit
        const ratio = ((lowCostDeposit / allDeposits) * 100).toFixed(1)
        depositData.value.lowCostRatio = `${ratio}%`
        
        // 计算低成本存款占比的同比变化
        if (demandDepositData.length >= 2 && personalDepositData.length >= 2 && allDepositsData.length >= 2) {
          const demandDepositPrev = parseFloat(demandDepositData[1][3] || demandDepositData[1].index_vl || demandDepositData[1].index_value || 0)
          const personalDepositPrev = parseFloat(personalDepositData[1][3] || personalDepositData[1].index_vl || personalDepositData[1].index_value || 0)
          const allDepositsPrev = parseFloat(allDepositsData[1][3] || allDepositsData[1].index_vl || allDepositsData[1].index_value || 0)
          
          if (allDepositsPrev > 0) {
            const lowCostDepositPrev = demandDepositPrev + personalDepositPrev
            const prevRatio = (lowCostDepositPrev / allDepositsPrev) * 100
            const ratioChange = (parseFloat(ratio) - prevRatio).toFixed(1)
            depositData.value.lowCostRatioChange = `${ratioChange > 0 ? '+' : ''}${ratioChange}%`
          }
        }
      }
      
      // 生成低成本存款占比趋势数据
      if (demandDepositData && personalDepositData && allDepositsData) {
        const minLength = Math.min(demandDepositData.length, personalDepositData.length, allDepositsData.length, 6)
        depositTrendData.value.lowCost = []
        for (let i = 0; i < minLength; i++) {
          const demandValue = parseFloat(demandDepositData[i][3] || demandDepositData[i].index_vl || demandDepositData[i].index_value || 0)
          const personalValue = parseFloat(personalDepositData[i][3] || personalDepositData[i].index_vl || personalDepositData[i].index_value || 0)
          const allDepositsValue = parseFloat(allDepositsData[i][3] || allDepositsData[i].index_vl || allDepositsData[i].index_value || 0)
          if (allDepositsValue > 0) {
            const lowCostRatio = ((demandValue + personalValue) / allDepositsValue) * 100
            const date = allDepositsData[i][0] || `${2024 + Math.floor(i / 12)}-${String((i % 12) + 1).padStart(2, '0')}`
            depositTrendData.value.lowCost.unshift({ value: lowCostRatio, date: date })
          }
        }
      }
    }

    // 处理最大十户存款比例
    if (topTenDepositResult.status === 'fulfilled' && topTenDepositResult.value) {
      console.log('最大十户存款比例API响应:', topTenDepositResult.value)
      const topTenData = topTenDepositResult.value.datas || topTenDepositResult.value.data
      const topTenRatioValue = parseFloat(topTenData?.[0]?.[3] || topTenData?.[0]?.index_vl || topTenData?.[0]?.index_value || 0)
      
      // 数据库中的值是小数形式（如0.1042），需要乘以100转换为百分比
      const topTenRatio = topTenRatioValue * 100
      depositData.value.topTenRatio = `${topTenRatio.toFixed(1)}%`
      
      // 计算最大十户存款比例的同比变化
      if (topTenData.length >= 2) {
        const topTenRatioPrevValue = parseFloat(topTenData[1][3] || topTenData[1].index_vl || topTenData[1].index_value || 0)
        const topTenRatioPrev = topTenRatioPrevValue * 100
        const ratioChange = (topTenRatio - topTenRatioPrev).toFixed(1)
        depositData.value.topTenRatioChange = `${ratioChange > 0 ? '+' : ''}${ratioChange}%`
      }
      
      // 生成最大十户存款比例趋势数据
      if (topTenData) {
        depositTrendData.value.topTen = topTenData.slice(0, 6).reverse().map((item, index) => {
          const value = parseFloat(item[3] || item.index_vl || item.index_value || 0) * 100 // 转换为百分比
          const date = item[0] || `${2024 + Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`
          return { value: value, date: date }
        })
      }
    }

    console.log('业务发展数据加载完成:', { loanData: loanData.value, depositData: depositData.value })
    
  } catch (error) {
    console.error('加载业务发展数据失败:', error)
    // 使用默认示例数据
    loanData.value = {
      totalAmount: '1250.35',
      totalGrowthRate: '+12.5%',
      retailRatio: '42.1%',
      retailRatioChange: '-2.3%',
      realEstateGrowthRate: '+25.8%',
      realEstateChange: '+5.2%'
    }
    depositData.value = {
      totalAmount: '1680.22',
      totalGrowthRate: '+8.5%',
      lowCostRatio: '55.2%',
      lowCostRatioChange: '-3.1%',
      topTenRatio: '23.8%',
      topTenRatioChange: '+1.2%'
    }
  }
}

// 加载数字化转型渠道数据
const loadDigitalData = async () => {
  try {
    console.debug('[RiskRadar] 开始加载数字化转型渠道数据...')
    
    const promises = channelIndicators.map(indicator => getIndicatorData(indicator.name))
    const results = await Promise.allSettled(promises)
    
    const channelData = []
    let totalCount = 0
    
    // 处理每个渠道的数据
    for (let i = 0; i < results.length; i++) {
      const result = results[i]
      const indicator = channelIndicators[i]
      
      if (result.status === 'fulfilled' && result.value) {
        if (result.value.datas && result.value.datas.length > 0) {
          const latestData = result.value.datas[0]
          const count = parseFloat(latestData[3] || latestData.index_vl || latestData.index_value || 0)
          
          channelData.push({
            name: indicator.displayName,
            value: count,
            originalName: indicator.name
          })
          totalCount += count
        } else {
          channelData.push({
            name: indicator.displayName,
            value: 0,
            originalName: indicator.name
          })
        }
      } else {
        channelData.push({
          name: indicator.displayName,
          value: 0,
          originalName: indicator.name
        })
      }
    }
    
    // 计算占比
    digitalChannelData.value = channelData.map(item => ({
      name: item.name,
      value: totalCount > 0 ? parseFloat(((item.value / totalCount) * 100).toFixed(2)) : 0,
      actualValue: item.value,
      originalName: item.originalName
    }))
    
    console.log('数字化转型渠道数据加载完成:', digitalChannelData.value)
    
  } catch (error) {
    console.error('加载数字化转型数据失败:', error)
    // 使用默认模拟数据
    digitalChannelData.value = channelIndicators.map((indicator, index) => ({
      name: indicator.displayName,
      value: parseFloat((Math.random() * 20 + 5).toFixed(2)),
      actualValue: Math.random() * 1000000 + 100000,
      originalName: indicator.name
    }))
  }
}

// 初始化或更新数字化饼图
const initOrUpdateDigitalChart = async () => {
  await nextTick()
  
  console.log('[RiskRadar] 初始化数字化饼图...')
  console.log('[RiskRadar] digitalChartRef:', digitalChartRef.value)
  console.log('[RiskRadar] digitalChannelData:', digitalChannelData.value)
  
  if (!digitalChartRef.value) {
    console.warn('[RiskRadar] digitalChartRef 未找到')
    return
  }
  
  if (digitalChannelData.value.length === 0) {
    console.warn('[RiskRadar] 数字化渠道数据为空')
    return
  }
  
  // 每次都重新创建实例，避免切换问题
  if (digitalChartInstance) {
    digitalChartInstance.dispose()
    digitalChartInstance = null
  }
  
  digitalChartInstance = echarts.init(digitalChartRef.value)
  console.log('[RiskRadar] ECharts 实例已创建')
  
  const option = {
    color: ['#29D9D5', '#3C8BFF', '#4A5DDE', '#5A3EC8', '#FF6B9D', '#FF8C42', '#6BCF7F', '#FFD93D'],
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        const actualValue = params.data.actualValue
        const originalName = params.data.originalName || params.name
        
        let formattedValue = actualValue.toLocaleString()
        if (actualValue >= 10000) {
          formattedValue = (actualValue / 10000).toFixed(2) + '万笔'
        } else {
          formattedValue = actualValue.toLocaleString() + '笔'
        }
        
        return `${params.name}<br/>指标: ${originalName}<br/>交易数量: ${formattedValue}<br/>占比: ${params.value}%`
      },
      backgroundColor: 'rgba(0,0,0,0.7)',
      textStyle: {
        color: '#fff'
      }
    },
    legend: {
      show: false
    },
    series: [{
      type: 'pie',
      radius: ['30%', '55%'],
      center: ['50%', '50%'],
      data: digitalChannelData.value,
      label: {
        show: true,
        color: '#fff',
        fontSize: 9,
        formatter: (params) => {
          return `${params.name}\n${params.value}%`
        }
      },
      labelLine: {
        show: true,
        lineStyle: {
          color: '#fff'
        }
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  digitalChartInstance.setOption(option)
  console.log('[RiskRadar] 数字化饼图配置已设置')
}

// 切换到下一组指标
const switchToNextGroup = async () => {
  if (isTransitioning.value) return // 防止重复触发
  
  isTransitioning.value = true
  
  // 切换到下一组
  currentGroupIndex.value = (currentGroupIndex.value + 1) % businessGroups.length
  currentGroupName.value = businessGroups[currentGroupIndex.value].groupName
  
  // 延迟重置转换状态，确保动画完成
  setTimeout(() => {
    isTransitioning.value = false
  }, 600) // 与CSS动画时间匹配
}

// 启动自动轮播（每10秒，悬停暂停）
const startCarousel = () => {
  if (carouselTimer) clearInterval(carouselTimer)
  carouselTimer = setInterval(() => {
    if (!isPaused.value) {
      switchToNextGroup()
    }
  }, 100000)
}

// 停止轮播
const stopCarousel = () => {
  if (carouselTimer) {
    clearInterval(carouselTimer)
    carouselTimer = null
  }
}

// 监听当前组变化，更新饼图
watch(currentGroupIndex, async (newIndex) => {
  if (businessGroups[newIndex].key === 'digital') {
    // 等待过渡动画完成和 DOM 更新
    await nextTick()
    setTimeout(() => {
      initOrUpdateDigitalChart()
    }, 700) // 增加延迟，确保过渡动画完成（600ms动画 + 100ms缓冲）
  }
})

onMounted(async () => {
  await loadBusinessData()
  await loadDigitalData()
  
  // 延迟启动轮播，确保数据加载完成
  setTimeout(() => {
    startCarousel()
  }, 3000)
})

onUnmounted(() => {
  stopCarousel()
  if (digitalChartInstance) {
    digitalChartInstance.dispose()
    digitalChartInstance = null
  }
})
</script>

<style scoped>
/* 业务容器 */
.business-container {
  height: 100%;
  position: relative;
}

.metrics-group {
  height: 100%;
}

.metrics-container {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 4px;
  height: 100%;
  align-items: stretch;
  width: 100%;
  padding: 2px 0;
}

/* 标题内容容器 */
.tit-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  position: relative;
}

.tit-main {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  flex: 1;
}

/* 组名显示样式 - 透明风格 */
.group-name {
  font-size: 12px;
  color: white;
  font-weight: 500;
  background: rgba(255, 107, 107, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
  border: 1px solid rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
  white-space: nowrap;
}


/* 组切换动画效果 */
.group-fade-enter-active,
.group-fade-leave-active {
  transition: all 0.6s ease;
}

.group-fade-enter-from {
  opacity: 0;
  transform: translateX(20px);
}

.group-fade-leave-to {
  opacity: 0;
  transform: translateX(-20px);
}

/* 组名切换动画 */
.group-name-fade-enter-active,
.group-name-fade-leave-active {
  transition: all 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.group-name-fade-enter-from {
  opacity: 0;
  transform: translateY(-15px) scale(0.8);
  filter: blur(2px);
}

.group-name-fade-leave-to {
  opacity: 0;
  transform: translateY(15px) scale(0.8);
  filter: blur(2px);
}


.metric-item {
  padding: 10px 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border-left: 3px solid #29D9D5;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  min-height: 185px;
  transition: all 0.3s ease;
  overflow: hidden;
  box-sizing: border-box;
}

.metric-item:hover {
  background: rgba(255, 255, 255, 0.08);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(41, 217, 213, 0.2);
}

.metric-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 0;
  flex: 1;
  height: 100%;
  justify-content: space-between;
}

.metric-info {
  flex: 0 0 auto;
  min-width: 0; /* 允许文本截断 */
  width: 100%;
  margin-bottom: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.metric-chart {
  flex: 1;
  width: 100%;
  margin-top: auto;
  padding-top: 10px;
  min-height: 60px;
  display: flex;
  align-items: flex-end;
  overflow: hidden;
  max-width: 100%;
}

/* 竖向布局下让迷你趋势图占满整行宽度并充分利用空间 */
.metric-chart svg {
  width: 100% !important;
  height: 45px;
  display: block;
  max-width: 100%;
}

/* 趋势图容器样式优化 */
.metric-chart .mini-trend-chart,
.metric-chart .mini-trend-chart_ver {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.metric-chart .mini-trend-chart .trend-indicator,
.metric-chart .mini-trend-chart_ver .trend-indicator {
  margin-top: 6px;
  align-self: flex-start;
}

.metric-label {
  color: rgba(255, 255, 255, 0.85);
  font-size: 12px;
  line-height: 1.4;
  margin-bottom: 8px;
  font-weight: 500;
  letter-spacing: 0.3px;
  white-space: nowrap;
  text-align: center;
  width: 100%;
}

.metric-value {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  width: 100%;
  max-width: 100%;
  overflow: hidden;
}

.value-main {
  display: flex;
  align-items: baseline;
  gap: 1px;
  line-height: 1;
  max-width: 100%;
  overflow: hidden;
  flex-wrap: nowrap;
}

.value-change-row {
  display: flex;
  /* align-items: center; */
  margin-left:5px;
  gap: 8px;
  width: 100%;
}

.value {
  color: #29D9D5;
  font-size: 18px;
  font-weight: 600;
  font-family: 'Roboto', 'Microsoft YaHei', sans-serif;
  letter-spacing: -0.8px;
  flex-shrink: 0;
  white-space: nowrap;
}

.value-unit {
  color: rgba(255, 255, 255, 0.7);
  font-size: 9px;
  font-weight: 400;
  margin-left: 1px;
  transform: translateY(-2px);
  flex-shrink: 0;
  white-space: nowrap;
}

.value-change {
  font-size: 11px;
  font-weight: 600;
  padding: 4px 10px;
  border-radius: 12px;
  position: relative;
  overflow: hidden;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  border: 1px solid transparent;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 3px;
  white-space: nowrap;
}

.change-up {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8a80 100%);
  color: #fff;
  border-color: rgba(255, 107, 107, 0.4);
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.change-down {
  background: linear-gradient(135deg, #00d4aa 0%, #4ecdc4 100%);
  color: #fff;
  border-color: rgba(0, 212, 170, 0.4);
  box-shadow: 0 2px 8px rgba(0, 212, 170, 0.3);
}

.value-change:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.change-type {
  font-size: 10px;
  opacity: 0.9;
  margin-right: 3px;
  font-weight: 400;
  letter-spacing: 0.3px;
}

.trend {
  font-size: 10px;
}

.trend.up {
  color: #ff6b6b; /* 上升用红色 */
}

.trend.down {
  color: #00ff00; /* 下降用绿色 */
}

/* 数字化转型饼图容器 */
.digital-chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.digital-chart {
  width: 100%;
  height: 200px;
}

/* 响应式设计：项目仅面向大屏，已移除小屏媒体查询 */
</style>
